﻿using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using UIWindows.Domains;
using UIWindows.Enums;
using UIWindows.GlobalStatics;
using UIWindows.Models;
using UIWindows.Models.Devices;
using UIWindows.Models.ParameterModels;
using UIWindows.Services.Context;
using UIWindows.Services.PLC_MESHelper;
using UIWindows.Tools.Helper;
using UIWindows.Views;
using XingLucifer.Devices;
using XingLucifer.IBase;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models;

namespace UIWindows.Services
{
    public class TaskService
    {
        private CancellationTokenSource _taskToken;
        private Dictionary<string, object> _tasks = default;
        private ConcurrentDictionary<string, object> _taskcd = default;
        #region 单例模式
        private static readonly object _lock = new object();
        private static TaskService taskService = default;

        public static TaskService Instance
        {
            get
            {
                if (taskService == null)
                {
                    lock (_lock)
                    {
                        if (taskService == null)
                        {
                            taskService = new TaskService();
                        }
                    }
                }
                return taskService;
            }
        }
        #endregion
        private SystemConfigStatic _systemConfigStatic;
        private DeviceConfigStatic _deviceConfig;
        private TemporaryStatic _temporaryStatic;
        private ParameterStatic _parameterStatic;

        private UserConfigStatic _userConfigStatic;
        private HomeStatic _homeStatic;

        private ReserveStatic _reserve;

        private DeviceInteractiveaddressStatic _deviceInteractiveaddressStatic;
        Action<string, string, string, string, string, long, DateTime, string, string, string, string> _log;
        private TaskService()
        {
            _taskToken = new CancellationTokenSource();
            _tasks = new Dictionary<string, object>();
            _taskcd = new ConcurrentDictionary<string, object>();
            _systemConfigStatic = ObjectContainer.ResolveSingleton<SystemConfigStatic>();
            _deviceConfig = ObjectContainer.ResolveSingleton<DeviceConfigStatic>();
            _temporaryStatic = ObjectContainer.ResolveSingleton<TemporaryStatic>();
            _parameterStatic = ObjectContainer.ResolveSingleton<ParameterStatic>();

            _deviceInteractiveaddressStatic = ObjectContainer.ResolveSingleton<DeviceInteractiveaddressStatic>();

            _userConfigStatic = ObjectContainer.ResolveSingleton<UserConfigStatic>();
            _homeStatic = Domains.ObjectContainer.ResolveSingleton<HomeStatic>();

            _reserve = ObjectContainer.ResolveSingleton<ReserveStatic>();
            _log = DialogLogHelper.MesLog;
            
        }

        private void InitTask()
        {
            _temporaryStatic.DeviceStatus.Clear();
            _tasks.Clear();
            foreach (var signal in _systemConfigStatic.SignalList)
            {
                _temporaryStatic.DeviceStatus.Add(signal.Name, 0);
                //var iAddressList = _systemConfigStatic.IAddressList.Where(x => x.ServiceName == signal.Name);
                var iAddressList = _deviceConfig.DeviceList.Where(x => x.ServiceName == signal.Name);
                foreach (var item in iAddressList)
                {
                    var handlerType = typeof(Context.DataContext);
                    object? obj = Activator.CreateInstance(handlerType);

                    _tasks.Add($"{signal.Name}{item.TaskType.GetHashCode()}{item.DeviceType.GetHashCode()}{item.Index}", obj);
                }
            }
        }
        public async Task<bool> SwitchOn()
        {
            if (_taskToken.Token.IsCancellationRequested) { _taskToken = new CancellationTokenSource(); }
            if (await DeviceLink())
            {
                try
                {
                     _ = $"启动成功 \r\n\r\nMES已经{(_parameterStatic.DecideParameter.EnableMES? "开启" : "关闭")}".MessageDialogs(MessageLevelType.成功, true, PopUpTypes.Global);
                    _temporaryStatic.IsRunStatus = true;
                    _temporaryStatic.ExcisionList.Clear();
                    _temporaryStatic.IsExcision = System.Windows.Visibility.Collapsed;
                    //int i = 0;
                    //InitTask();
                    //循环扫描信号
                    foreach (var item in _systemConfigStatic.SignalList)
                    {
                        var model = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == item.Name);
                        if (item.DeviceType == DeviceTypes.NONE|| model == null)
                        {
                            continue;
                        }
                       

                        var serviceList = _temporaryStatic.LinkList.FirstOrDefault(x => x.ServiceName == "上位机状态");
                        if (serviceList != null) { serviceList.Status = true; }
                        

                        // 遍历枚举中的所有值
                        foreach (MachineInfoTypes machineInfoType in Enum.GetValues(typeof(MachineInfoTypes)))
                        {
                            // 检查字典中是否存在枚举值对应的键
                            if (!_parameterStatic.MESCollectionItemsParameter.ContainsKey(machineInfoType))
                            {
                                // 如果不存在，则添加该键值对
                                _parameterStatic.MESCollectionItemsParameter.Add(machineInfoType, new MESCollectionItemsParameterModel());
                            }
                        }

                        int count_Heartbeat = 0;
                        Models.Interact.ScanSignalModel ssModel = item;//扫描信号
                                                                       //心跳地址
                                                                       //ssModel.Heartbeat
                                                                       //bool[] bools = new bool[ssModel.Length_Resection];
                                                                       //var taskList = new Dictionary<string, object>();
                                                                       //foreach (var item in _tasks.Where(x => x.Key.Contains(ssModel.Name)))
                                                                       //{
                                                                       //    taskList.Add(item.Key, item.Value);
                                                                       //}
                        var plc = _deviceConfig.DeviceList.FirstOrDefault(t => t.DeviceType == ssModel.DeviceType && t.ServiceName == ssModel.Name);
                        //if(plc.ServiceName == MachineInfoTypes.装盘机.ToString()|| plc.ServiceName == MachineInfoTypes.拆盘机.ToString())
                        //{
                        //    plc= _deviceConfig.DeviceList.FirstOrDefault(t => t.DeviceType == ssModel.DeviceType 
                        //    && t.ServiceName == ssModel.Name&&t.Index==i);
                        //    i++;
                        //}

                        if (plc == null || plc.Index == 999)
                        {
                            continue;
                        }


                        _ = Task.Run(async() =>
                        {
                            try
                            {
                                $"扫描线程 [{item.Name}] 启动".RunLog(MessageLevelType.信息);
                                var plc_KVPLC = plc.PLC ;

                                Models.Interact.PLCSignalModel signalData = new Models.Interact.PLCSignalModel(ssModel.Length_Signal, ssModel.Length_Resection);
                                StringBuilder key = new StringBuilder();
                                int count = 0;

                                #region 计时器
                                ////计时器
                                //Stopwatch stopwatch = new Stopwatch();
                                ////开始计时
                                //stopwatch.Start();
                                //// 停止计时
                                //stopwatch.Stop();
                                //// 获取经过的毫秒数
                                //long elapsedMilliseconds = plcBaseOperateStopwatch.ElapsedMilliseconds;
                                ////获取计时的秒
                                //double elapsedSeconds = stopwatch.Elapsed.TotalSeconds;
                                ////获取计时的分钟
                                //double elapsedMinutes = stopwatch.Elapsed.TotalMinutes;
                                //// //获取计时的小时
                                //double elapsedHours = stopwatch.Elapsed.TotalHours;

                                //// 停止并重置计时器
                                //stopwatch.Reset();
                                #endregion

                                #region 触摸屏基础操作类，登录、获取工单、执行工单等
                                var plcBaseOperate = new PLCBaseOperateHelper(
                                         _deviceInteractiveaddressStatic,
                                     plc,
                                     _temporaryStatic,
                                     _parameterStatic,
                                     _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );
                                //plcBaseOperate.TaskWorkOrderTest();
                                //触摸屏基础操作计时器
                                Stopwatch plcBaseOperateStopwatch = new Stopwatch();
                                plcBaseOperateStopwatch.Start();
                                #endregion

                                #region 设备状态
                                var deviceStatusHelper = new DeviceStatusHelper(
                                       _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );
                                //设备状态计时器
                                Stopwatch deviceStatusStopwatch = new Stopwatch();
                                deviceStatusStopwatch.Start();
                                #endregion




                                #region 工艺参数采集存入数据库 对比标准参数不合格调用超限接口

                                var MESParameterHelper = new ProcessParameterHelper(
                                        _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );
                                Stopwatch mesParameterStopwatch = new Stopwatch();
                                mesParameterStopwatch.Start();
                                //_=MESParameterHelper.Handle();


                                #endregion

                                #region 工艺参数上传MES

                                var _parameterUploadHelper = new ProcessParameterUploadHelper(
                                          _deviceInteractiveaddressStatic,
                                     plc,
                                     _temporaryStatic,
                                     _parameterStatic,
                                     _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );
                                Stopwatch _parameterUploadStopwatch = new Stopwatch();
                                _parameterUploadStopwatch.Start();
                                //_=MESParameterHelper.Handle();


                                #endregion


                                #region 产量信息采集获取


                                var _productionHelper = new ProductionHelper(
                                      _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );

                                //定时获取产量
                                Stopwatch _productionStopwatch = new Stopwatch();
                                _productionStopwatch.Start();

                                //产量信息小时上传MES计时器
                                Stopwatch _productionHourStopwatch = new Stopwatch();
                                _productionHourStopwatch.Start();
                                //产量信息天上传MES计时器
                                Stopwatch _productionDayStopwatch = new Stopwatch();
                                _productionDayStopwatch.Start();

                                #endregion

                                #region 卷芯上料左右扫码检测
                                var _coilCoreLoadingLeftScan = new CoilCoreLoadingLeftScanBarcode(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );

                                var _coilCoreLoadingRightScan = new CoilCoreLoadingRightScanBarcode(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );
                                Stopwatch _coilCoreLoadingScanStopwatch = new Stopwatch();
                                if (plc.ServiceName == MachineInfoTypes.卷芯上料.ToString())
                                {
                                    _coilCoreLoadingScanStopwatch.Start();
                                }

                                #endregion

                                #region 拆盘机左右扫码检测
                                var _dismantlingDiscLeftScan = new DismantlingDiscLeftScanBarcode(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );

                                var _dismantlingDiscRightScan = new DismantlingDiscRightScanBarcode(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );

                                Stopwatch _dismantlingDiscStopwatch = new Stopwatch();
                                if (plc.ServiceName.Contains("拆盘机"))
                                {
                                    _dismantlingDiscStopwatch.Start();
                                }

                                #endregion

                                #region 装盘机左右扫码检测
                                var _trayFillerLeftScan = new TrayFillerLeftScanBarcode(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );

                                var _trayFillerRightScan = new TrayFillerRightScanBarcode(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );

                                Stopwatch _trayFillerScanStopwatch = new Stopwatch();
                                if (plc.ServiceName.Contains("装盘机"))
                                {
                                    _trayFillerScanStopwatch.Start();
                                }

                                #endregion

                                #region 预充
                                Stopwatch _plateScanStopwatch = new Stopwatch();

                                if (_deviceConfig.DeviceList.Any(x => x.ServiceName == MachineInfoTypes.预充装盘.ToString()))
                                {
                                    _plateScanStopwatch.Start();
                                }


                                ///前扫码
                                var _beforeScanBarcodeHandler = new BeforeScanBarcodeHandler(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );
                                //前扫码处理信号，1接收信号中，99正在处理中
                                int _beforeScanBarcode_load  = 1;

                                ///后扫码
                                var _afterScanBarcodeHandler = new AfterScanBarcodeHandler(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );
                                //后扫码处理信号，1接收信号中，99正在处理中
                                int _afterScanBarcode_load = 1;


                                ///预充行装盘
                                var _rowPlateFinishedHandler = new RowPlateFinishedHandler(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );
                                //预充行装盘处理信号，1接收信号中，99正在处理中
                                int _rowPlateFinished_load = 1;


                                ///清扫码队列1
                                var _initBarcode1Handler = new InitBarcode1Handler(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );

                                ///清扫码队列2
                                var _initBarcode2Handler = new InitBarcode2Handler(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );
                                //清扫码队列处理信号，1接收信号中，99正在处理中
                                int _initBarcode_load = 1;

                                
                                ///托盘扫码
                                var _plateScanBarcodeHandler = new PlateScanBarcodeHandler(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog,
                                 _reserve
                                 );

                                //托盘扫码处理信号，1接收信号中，99正在处理中
                                int _plateScanBarcode_load = 1;

                                
                                ///装盘完成
                                var _plateFinishedHandler = new PlateFinishedHandler(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog,
                                 _reserve
                                 );

                                //托盘扫码处理信号，1接收信号中，99正在处理中
                                int _plateFinished_load = 1;



                                
                                ///下料托盘扫码
                                var _blankingScanBarcodeHandler = new BlankingScanBarcodeHandler(
                                 _deviceInteractiveaddressStatic,
                                 plc,
                                 _temporaryStatic,
                                 _parameterStatic,
                                 _deviceConfig,
                                   _systemConfigStatic,
                                    _homeStatic,
                                 DialogLogHelper.MesLog, DialogLogHelper.MESDialog
                                 );

                                //下料托盘扫码处理信号，1接收信号中，99正在处理中
                                int _blankingScanBarcode_load = 1;



                                #endregion



                                MESCollectionItemsParameterModel _parameter = null;
                                var machineInfoType = (MachineInfoTypes)Enum.Parse(typeof(MachineInfoTypes), plc.ServiceName);
                                if (_parameterStatic.MESCollectionItemsParameter != null && _parameterStatic.MESCollectionItemsParameter.ContainsKey(machineInfoType))
                                {
                                    _parameter = _parameterStatic.MESCollectionItemsParameter[machineInfoType];
                                    //_parameter = _parameterStatic.MESCollectionItemsParameter[machineInfoType];
                                }
                                #region 标准工艺参数获取更新保存
                                //计时器
                                Stopwatch _pumDataSaveStopwatch = new Stopwatch();
                                _pumDataSaveStopwatch.Start();
                                #endregion
                                while (!_taskToken.Token.IsCancellationRequested)
                                {
                                    try
                                    {
                                        //Thread.Sleep(1000);
                                        //continue;
                                        //心跳
                                        if (!string.IsNullOrWhiteSpace(ssModel.Heartbeat))
                                        {
                                            count_Heartbeat++;
                                            if (count_Heartbeat >= 10)
                                            {
                                                plc_KVPLC.Write<short>(ssModel.Heartbeat, new short[] { 1 });

                                                count_Heartbeat = 0;
                                            }
                                        }

                                        #region 预充
                                        if (plc.ServiceName == MachineInfoTypes.预充装盘.ToString())
                                        {
                                            //var addressListModel = _systemConfigStatic.IAddressList.Where(x => x.ServiceName == ssModel.Name).ToList();
                                            //if (addressListModel != null&& addressListModel.Count!=0)
                                            //{ 
                                            //}

                                            //定时检测是否触发扫码50毫秒一次
                                            if (_plateScanStopwatch.ElapsedMilliseconds >= 50)
                                            {
                                                _plateScanStopwatch.Reset();
                                                var values = plc_KVPLC.Read("DM1000", 56);
                                                if (values != null && values.Count >= 56)
                                                {
                                                    var DM1001 = values[1];
                                                    var DM1004 = values[4];

                                                    var DM1000 = values[0];
                                                    var DM1002 = values[2];
                                                    var DM1003 = values[3];
                                                    var DM1005 = values[5];
                                                    var DM1006 = values[6];
                                                    var DM1008 = values[8];
                                                    var DM1010 = values[10];
                                                    //前扫码
                                                    if (DM1000 == 1 && _beforeScanBarcode_load == 1)
                                                    {
                                                        _ = Task.Run(() =>
                                                        {
                                                            _beforeScanBarcode_load = 99;
                                                            _beforeScanBarcodeHandler.Handle();
                                                        }).ContinueWith(x =>
                                                        {
                                                            _beforeScanBarcode_load = 1;
                                                        });
                                                    }
                                                    //后扫码
                                                    if (DM1002 == 1 && _afterScanBarcode_load == 1)
                                                    {
                                                        _ = Task.Run(() =>
                                                        {
                                                            _afterScanBarcode_load = 99;
                                                            _afterScanBarcodeHandler.Handle();
                                                        }).ContinueWith(x =>
                                                        {
                                                            _afterScanBarcode_load = 1;
                                                        });
                                                    }
                                                    //预充行装盘
                                                    if (DM1003 == 1 && _rowPlateFinished_load == 1)
                                                    {
                                                        _ = Task.Run(() =>
                                                        {
                                                            _rowPlateFinished_load = 99;
                                                            _rowPlateFinishedHandler.Handle();
                                                        }).ContinueWith(x =>
                                                        {
                                                            _rowPlateFinished_load = 1;
                                                        });
                                                    }

                                                    //清扫码队列 
                                                    if ((DM1005 == 1 || DM1005 == 2) && _initBarcode_load == 1)
                                                    {
                                                        _ = Task.Run(() =>
                                                        {
                                                            _initBarcode_load = 99;
                                                            if (DM1005 == 1)
                                                            {
                                                                _initBarcode1Handler.Handle();
                                                            }
                                                            else
                                                            {
                                                                _initBarcode2Handler.Handle();
                                                            }

                                                        }).ContinueWith(x =>
                                                        {
                                                            _initBarcode_load = 1;
                                                        });
                                                    }

                                                    //托盘扫码
                                                    if (DM1006 == 1 && _plateScanBarcode_load == 1)
                                                    {
                                                        _ = Task.Run(() =>
                                                        {
                                                            _plateScanBarcode_load = 99;
                                                            _plateScanBarcodeHandler.Handle();

                                                        }).ContinueWith(x =>
                                                        {
                                                            _plateScanBarcode_load = 1;
                                                        });
                                                    }

                                                    ////装盘完成
                                                    if (DM1008 == 1 && _plateFinished_load == 1)
                                                    {
                                                        _ = Task.Run(() =>
                                                        {
                                                            _plateFinished_load = 99;
                                                            _plateFinishedHandler.Handle();

                                                        }).ContinueWith(x =>
                                                        {
                                                            _plateFinished_load = 1;
                                                        });
                                                    }

                                                    //托盘下料扫码
                                                    if (DM1010 == 1 && _blankingScanBarcode_load == 1)
                                                    {
                                                        _ = Task.Run(() =>
                                                        {
                                                            _blankingScanBarcode_load = 99;
                                                            _blankingScanBarcodeHandler.Handle();

                                                        }).ContinueWith(x =>
                                                        {
                                                            _blankingScanBarcode_load = 1;
                                                        });
                                                    }



                                                }

                                                _plateScanStopwatch.Start();
                                            }
                                        }


                                        //if (plc.ServiceName == MachineInfoTypes.预充装盘.ToString())
                                        //{
                                        //    continue;
                                        //}

                                        #endregion

                                        #region (ms)间隔检测 触摸屏是否有登录、获取工单、执行工单等操作,间隔时间  取工号校验间隔时间
                                        if (plc.ServiceName != MachineInfoTypes.预充装盘.ToString()&&plcBaseOperateStopwatch.ElapsedMilliseconds >= _parameterStatic.MESParameter.AccountNumber)
                                        {
                                            //// 停止并重置计时器
                                            plcBaseOperateStopwatch.Reset();
                                            // 任务完成后重新启动定时器
                                            //_=plcBaseOperate.Handle().ContinueWith(task =>
                                            //{
                                            //    plcBaseOperateStopwatch.Start();
                                            //});
                                            _ = Task.Run(() =>
                                            {
                                                plcBaseOperate.Handle();
                                            }).ContinueWith(x =>
                                            {
                                                plcBaseOperateStopwatch.Start();
                                            });
                                        }

                                        #endregion



                                        //未登录不检测
                                        if (_parameter == null|| string.IsNullOrWhiteSpace(_parameter.EquipmentCode)
                                        || string.IsNullOrWhiteSpace(_parameter.WorkOrder)
                                            || !_deviceInteractiveaddressStatic.BaseParameters.ContainsKey(machineInfoType)
                                         )
                                        {
                                            continue;
                                        }


                                        #region (ms)间隔检测 检测设备状态是否改变  取设备履历间隔时间
                                        if (deviceStatusStopwatch.ElapsedMilliseconds >= _parameterStatic.MESParameter.EquipmentStatusNumber)
                                        {
                                            deviceStatusStopwatch.Reset();
                                            //_ = deviceStatusHelper.Handle().ContinueWith(task =>
                                            //{
                                            //    deviceStatusStopwatch.Start();
                                            //});

                                            _ = Task.Run(() =>
                                            {
                                                deviceStatusHelper.Handle();
                                            }).ContinueWith(x =>
                                            {
                                                deviceStatusStopwatch.Start();
                                            });
                                        }
                                        #endregion



                                        #region (ms)间隔采集 采集工艺参数  只要检测到有新的cdd结果就采集
                                        if (plc.ServiceName != MachineInfoTypes.预充装盘.ToString() && mesParameterStopwatch.ElapsedMilliseconds >= 300)
                                        {
                                            mesParameterStopwatch.Reset();
                                            _ = Task.Run(() =>
                                            {
                                                MESParameterHelper.Handle();
                                            }).ContinueWith(x =>
                                            {
                                                mesParameterStopwatch.Start();
                                            });


                                        }
                                        #endregion


                                        #region (ms)间隔采集更新标准工艺参数
                                        {
                                            if (plc.ServiceName != MachineInfoTypes.预充装盘.ToString() && _pumDataSaveStopwatch.ElapsedMilliseconds >= _parameterStatic.MESParameter.GeneralDataNumber)
                                            {
                                                _pumDataSaveStopwatch.Reset();
                                                 _ = Task.Run(() =>
                                                {
                                                    MESParameterHelper.PumDataSave();
                                                }).ContinueWith(x =>
                                                {
                                                    _pumDataSaveStopwatch.Start();
                                                });
                                            }

                                        }
                                        #endregion


                                        #region (ms)间隔上传 工艺参数间隔上传MES  间隔时间取工艺参数接口间隔时间
                                        if (plc.ServiceName != MachineInfoTypes.预充装盘.ToString() && _parameterUploadStopwatch.ElapsedMilliseconds >= _parameterStatic.MESParameter.EquipUploadParamNumber)
                                        {
                                            _parameterUploadStopwatch.Reset();
                                            _ = Task.Run(() =>
                                            {
                                                _parameterUploadHelper.Handle();
                                            }).ContinueWith(x =>
                                            {
                                                _parameterUploadStopwatch.Start();
                                            });


                                        }
                                        #endregion

                                        #region (ms)间隔采集 采集产量信息小时，和天接口


                                        //定时上传采集产量，每1秒一次
                                        if (_productionStopwatch.ElapsedMilliseconds >= 1000)
                                        {
                                            _productionStopwatch.Reset();
                                            _ = Task.Run(() =>
                                            {
                                                _productionHelper.Handle();
                                            }).ContinueWith(x =>
                                            {
                                                _productionStopwatch.Start();
                                            });
                                        }

                                        //小时产量接口定时上传
                                        if (_productionHourStopwatch.ElapsedMilliseconds >= _parameterStatic.MESParameter.ProductCountDataNumber)
                                        {
                                            _productionHourStopwatch.Reset();
                                            _ = Task.Run(() =>
                                            {
                                                _productionHelper.TaskCountHour_Elapsed();
                                            }).ContinueWith(x =>
                                            {
                                                _productionHourStopwatch.Start();
                                            });
                                        }
                                        
                                        //天产量接口定时上传
                                        if (_productionDayStopwatch.ElapsedMilliseconds >= _parameterStatic.MESParameter.ProductCountData_DayNumber)
                                        {
                                            _productionDayStopwatch.Reset();
                                            _ = Task.Run(() =>
                                            {
                                                _productionHelper.TaskCountDay_Elapsed();
                                            }).ContinueWith(x =>
                                            {
                                                _productionDayStopwatch.Start();
                                            });
                                        }


                                        #endregion

                                        #region 卷芯上料扫码交互地址
                                        if (plc.ServiceName == MachineInfoTypes.卷芯上料.ToString())
                                        {
                                            //定时检测是否触发左扫码或者右扫码100毫秒一次
                                            if (_coilCoreLoadingScanStopwatch.ElapsedMilliseconds >= 100)
                                            {
                                                _coilCoreLoadingScanStopwatch.Reset();
                                                //var values = plc_KVPLC.Read(addressListModel.Label, 1);
                                                var values = plc_KVPLC.Read("DM1000", 2);
                                                if (values != null && values.Count >= 2)
                                                {
                                                    var DM1000 = values[0];
                                                    var DM1001 = values[1];
                                                    if(DM1000==1)
                                                    {
                                                        _ = Task.Run(() =>
                                                        {
                                                            _coilCoreLoadingLeftScan.Handle();

                                                        }).ContinueWith(x =>
                                                        {
                                                            _coilCoreLoadingScanStopwatch.Start();
                                                        });
                                                        
                                                    }else if(DM1001==1)
                                                    {
                                                        _ = Task.Run(() =>
                                                        {
                                                            _coilCoreLoadingRightScan.Handle();

                                                        }).ContinueWith(x =>
                                                        {
                                                            _coilCoreLoadingScanStopwatch.Start();
                                                        });

                                                    }
                                                    else
                                                    {
                                                        _coilCoreLoadingScanStopwatch.Start();
                                                    }
                                                }
                                                else
                                                {
                                                    _coilCoreLoadingScanStopwatch.Start();
                                                }

                                            }
                                        }

                                        #endregion


                                        #region 拆盘机
                                        //if (plc.ServiceName.Contains("拆盘机")&&1==3)
                                        if (plc.ServiceName.Contains("拆盘机"))
                                        {
                                            //定时检测是否触发左扫码或者右扫码50毫秒一次
                                            if (_dismantlingDiscStopwatch.ElapsedMilliseconds >= 50)
                                            {
                                                _dismantlingDiscStopwatch.Reset();

                                                var values = plc_KVPLC.Read("DM1000", 2);

                                                if (values != null && values[0] == 1)
                                                {
                                                    _ = Task.Run(() =>
                                                    {
                                                        if (plc.ServiceName == MachineInfoTypes.左拆盘机.ToString())
                                                        {
                                                            _dismantlingDiscLeftScan.Handle();
                                                        }
                                                        else if (plc.ServiceName == MachineInfoTypes.右拆盘机.ToString())
                                                        {
                                                            _dismantlingDiscRightScan.Handle();
                                                        }

                                                    }).ContinueWith(x =>
                                                    {
                                                        _dismantlingDiscStopwatch.Start();
                                                    });
                                                }
                                                else
                                                {
                                                    _dismantlingDiscStopwatch.Start();
                                                }
                                            }

                                            
                                        }

                                        #endregion


                                        #region 装盘机
                                        if (plc.ServiceName.Contains("装盘机"))
                                        {
                                            //定时检测是否触发左扫码或者右扫码50毫秒一次
                                            if (_trayFillerScanStopwatch.ElapsedMilliseconds >= 50)
                                            {
                                                _trayFillerScanStopwatch.Reset();

                                                var values = plc_KVPLC.Read("DM1000", 2);


                                                if (values != null && values[0] == 1)
                                                {
                                                    _ = Task.Run(() =>
                                                    {
                                                        if(plc.ServiceName==MachineInfoTypes.左装盘机.ToString())
                                                        {
                                                            _trayFillerLeftScan.Handle();
                                                        }else if (plc.ServiceName == MachineInfoTypes.右装盘机.ToString())
                                                        {
                                                            _trayFillerRightScan.Handle();
                                                        }

                                                    }).ContinueWith(x =>
                                                    {
                                                        _trayFillerScanStopwatch.Start();
                                                    });
                                                }
                                                else
                                                {
                                                    _trayFillerScanStopwatch.Start();
                                                }

                                            }

                                            
                                        }

                                        #endregion




                                        //  #region 预充扫码交互地址
                                        //  if (plc.ServiceName == MachineInfoTypes.预充装盘.ToString()
                                        //&& _systemConfigStatic.IAddressList.Any(x => x.ServiceName == MachineInfoTypes.预充装盘.ToString()))

                                        //#endregion
                                    }
                                    catch (Exception ex)
                                    {
                                        $"主任务错误{ex}".RunLog(MessageLevelType.警告);
                                        _taskcd.Clear();
                                    }

                                    Thread.Sleep(20);
                                }

                                count = 0;
                                while (_taskcd.Count != 0)
                                {
                                    Thread.Sleep(500);
                                    if (count > 60)
                                    {
                                        _taskcd.Clear();
                                    }
                                    $"第 [{++count}] 次 等待所有任务退出.....".RunLog(MessageLevelType.警告);
                                }
                            }
                            catch (Exception ex)
                            {
                                $"扫描线程执行异常：{ex}".RunLog(MessageLevelType.错误);
                            }
                        }, _taskToken.Token).ContinueWith(sender =>
                        {

                            $"扫描线程退出运行".RunLog(MessageLevelType.警告);
                            //退出扫描线程后的任务
                            _taskcd.Clear();
                            _temporaryStatic.IsRunStatus = false;
                            CloseDevice();
                            ThreadHelper.CrossThread(x =>
                            {
                                if (_systemConfigStatic.SCM.PerformTaskName.Content.ToString() != "    运  行    ")
                                {
                                    _systemConfigStatic.SCM.PerformTaskName.Content = "    运  行    ";
                                    _systemConfigStatic.SCM.IsShowWarnTip = true;
                                    Color customColor = (Color)ColorConverter.ConvertFromString("#67C23A");
                                    _systemConfigStatic.SCM.PerformTaskName.Background = new SolidColorBrush(customColor);
                                }
                                if (DialogHost.IsDialogOpen(PopUpTypes.Global.ToString())) DialogHost.Close(PopUpTypes.Global.ToString());
                            }, 0);
                            var serviceList = _temporaryStatic.LinkList.FirstOrDefault(x => x.ServiceName == "上位机状态");
                            if (serviceList != null) { serviceList.Status = false; }

                        }).ConfigureAwait(false);
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    $"启动任务异常：{ex}".RunLog(MessageLevelType.错误);
                    _temporaryStatic.IsRunStatus = false;
                    return false;
                }
            }
            _ = "设备链接失败!!!\r\n前往日志系统查看详细设备.".MessageDialogs(MessageLevelType.错误, true, Enums.PopUpTypes.Global);
            _taskToken.Cancel();
            CloseDevice();
            return false;
        }

        private void CloseDevice()
        {
            foreach (var item in _deviceConfig.DeviceList)
            {
                if (item.Communication == null)
                {
                    if(item.PLC!=null)
                    {
                        item.PLC.Close();
                    }
                    continue;
                }
                try
                {
                    item.Communication.Close();
                    item.Communication = null;
                }
                catch (Exception ex)
                {
                    $"释放异常：{ex}".RunLog(MessageLevelType.信息);
                }
            }
        }

        public bool RemoveTask(Context.DataContext model) => _taskcd.TryRemove($"{model.ServiceName}{model.TaskType.GetHashCode()}{model.DeviceType.GetHashCode()}{model.Address_Struct}{model.DeviceIndex}", out _);
        public void SwitchOFF() => _taskToken.Cancel();

        public async Task<bool> DeviceLink()
        {
            return await Task.Run(() => Parallel.ForEach(_deviceConfig.DeviceList, (x, _parallelLoopState) =>
            {
                try
                {
                    //if (x.Index == 0 || string.IsNullOrEmpty(x.IPCOM) || x.Index == 999) { return; }
                    if (string.IsNullOrEmpty(x.IPCOM) || x.Index == 999) { return; }
                    ICommunication com = null;
                    EndianTypes endianTypes = EndianTypes.Fins;
                    //switch (x.DeviceType)
                    //{
                    //    case DeviceTypes.NJ_FINS_PLC:
                    //        endianTypes = EndianTypes.Fins;
                    //        break;
                    //    case DeviceTypes.Modbus_TCP_ABCD:
                    //        endianTypes = EndianTypes.Modbus_ABCD;
                    //        break;
                    //    case DeviceTypes.Modbus_TCP_BADC:
                    //        endianTypes = EndianTypes.Modbus_BADC;
                    //        break;
                    //    case DeviceTypes.Modbus_TCP_DCBA:
                    //        endianTypes = EndianTypes.Modbus_DCBA;
                    //        break;
                    //    case DeviceTypes.Modbus_TCP_CDAB:
                    //        endianTypes = EndianTypes.Modbus_CDAB;
                    //        break;
                    //    case DeviceTypes.CIP_Omron:
                    //        endianTypes = EndianTypes.CIP_Omron;
                    //        break;
                    //}
                    string errMessage = "设备连接失败：";
                    if(x.IsSocket&&x.DeviceType== DeviceTypes.KVPLC)
                    {
                        var plcModel= new KVPLC($"{x.IPCOM}:{x.Port}");
                        if (plcModel.Connection() == true)
                        {
                            x.PLC = plcModel;
                        }
                        else
                        {
                           
                            $"设备：[{x.ServiceName}] 序号：[{x.Index}] IP：[{x.IPCOM}] 端口号：[{x.Port}] 连接失败".RunLog(MessageLevelType.错误);
                           
                            errMessage += $"{x.ServiceName}、";
                        }


                    }else if (x.IsSocket && x.DeviceType == DeviceTypes.MelsecA1ENet)
                    {
                        var plcModel = new MelsecA1ENetMachine(1,$"{x.IPCOM}:{x.Port}");
                        if (plcModel.Connection() == true)
                        {
                            x.PLC = plcModel;
                        }
                        else
                        {

                            $"设备：[{x.ServiceName}] 序号：[{x.Index}] IP：[{x.IPCOM}] 端口号：[{x.Port}] 连接失败".RunLog(MessageLevelType.错误);

                            errMessage += $"{x.ServiceName}、";
                        }
                    }
                    else if (x.IsSocket)
                    {
                        com = new TCPCom(_systemConfigStatic.SCM.FinsIP, x.IPCOM, x.Port, x.DeviceType, x.Index, x.TaskType, x.ServiceName, _taskToken, endianTypes);

                        com.ReconnectDisconnection += Device_DropAlarms;
                        IDevices model = EquipmentFactory.NewSocketDevice(_systemConfigStatic.SCM.FinsIP, x.IPCOM, x.Port, x.DeviceType, x.Index, x.TaskType, x.ServiceName, _taskToken, com);
                        if (model == null)
                        {
                            return;
                        }
                        x.PLC = null;
                       bool ? bools = model.Open();
                        if (bools != null && bools == true)
                        {
                            //if (x.DeviceType == DeviceTypes.AND4531B_Scale
                            //|| x.DeviceType == DeviceTypes.TC06_Scale
                            //||x.DeviceType == DeviceTypes.TSC_L )
                            //{
                            //    _ = model.Read();
                            //}
                            x.Communication = model;
                        }
                        else
                        {
                            $"设备：[{x.TaskType}] 序号：[{x.Index}] IP：[{x.IPCOM}] 端口号：[{x.Port}] 连接失败".RunLog(MessageLevelType.错误);

                            errMessage += $"{x.ServiceName}、";
                        }
                    }
                    if(errMessage != "设备连接失败：")
                    {
                        _systemConfigStatic.SCM.HomeMessage = errMessage.TrimEnd('、') + "请检查设备是否开机" + "。请检查设备是否打开";
                        _parallelLoopState.Stop();
                    }
                    //else
                    //{
                    //    com = new SerialPortCom(_systemConfigStatic.SCM.FinsIP, x.IPCOM, x.Port,
                    //        System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One, x.DeviceType, x.Index, x.TaskType, x.ServiceName, _taskToken, endianTypes);
                    //}
                 
                }
                catch (Exception ex)
                {

                    $"设备：[{x.TaskType}] 序号：[{x.Index}] IP：[{x.IPCOM}] 端口号：[{x.Port}] 连接异常".RunLog(MessageLevelType.错误);
                }
                
            }).IsCompleted);
        }

        private bool Device_DropAlarms(ICommunication com, int index, string ipcom, int port, DeviceTypes deviceTypes, TaskTypes taskType, string serviceName, CancellationTokenSource token)
        {
            try
            {
                DeviceClientModel device = _deviceConfig.DeviceList.FirstOrDefault(t => t.DeviceType == deviceTypes && t.IPCOM == ipcom && t.Index == index && t.Port == port && t.TaskType == taskType && t.ServiceName == serviceName);
                if (token.Token.IsCancellationRequested || device.Communication == null)
                {
                    return false;
                }
                device.Communication.Close();
                //if (com.Types == DeviceTypes.注_CP1WCIF41 || com.Types == DeviceTypes.补_CP1WCIF41)
                //{
                //    $"{ipcom} 注液泵通信断开，重启网络模块......".RunLog(MessageLevelType.警告);
                //    string[] ip = ipcom.Split('.');
                //    if (ip[2].Restart_CP1WCIF41_Module(ip[3]))
                //    {
                //        Thread.Sleep(10000);//延时10S等待重启完成
                //        $"重启完成，重新发送指令".RunLog(MessageLevelType.警告);
                //    }
                //    else
                //    {
                //        $"重启注液泵执行失败".RunLog(MessageLevelType.错误);
                //    }
                //}
                Thread.Sleep(500);
                if (device.Communication!=null&&device.Communication.Open())
                {
                    $"设备：[{deviceTypes}] 序号：[{index}] IP：[{ipcom}] 端口号：[{port}]---重连成功！".RunLog(MessageLevelType.成功);
                    return true;
                }
                Thread.Sleep(500);
                $"设备：[{deviceTypes}] 序号：[{index}] IP：[{ipcom}] 端口号：[{port}]---重连失败...".RunLog(MessageLevelType.错误);
            }
            catch (Exception ex)
            {
                Thread.Sleep(500);
                $"设备重连异常：{ex}".RunLog(MessageLevelType.错误);
            }
            return false;
        }

        /// <summary>
        /// 设备状态上传送
        /// </summary>
        /// <param name="service_name"></param>
        private void UpdateDeviceStatus(string service_name)
        {

            //if (_temporaryStatic.DeviceStatus.ContainsKey(service_name))
            //{
            //    ThreadPool.QueueUserWorkItem(new WaitCallback(sende =>
            //    {
            //        var interaction = new OeeStatusInterface(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);
            //        Dictionary<string, object> param = new Dictionary<string, object>
            //    {
            //            { "machineNo", _parameterStatic.CollectionItemsParameter.EquipNum },
            //            { "producttype", _parameterStatic.CollectionItemsParameter.ProductType.ToString() },
            //    };
            //        while (!_taskToken.Token.IsCancellationRequested)
            //        {
            //            // 1:自动运行 , 2  待机, 3 报警,4 手动,5 故障状态,6 维修状态,7  急停状态                       
            //            int device_status = _temporaryStatic.DeviceStatus[sende.ToString()];
            //            int equipSign = device_status switch
            //            {
            //                var r when r == 1 => 1,
            //                var r when r == 2 => 2,
            //                var r when r == 5 => 3,
            //                var r when r == 6 => 4,
            //                var r when r == 7 => 5,
            //                _ => 6,
            //            };
            //            Dictionary<string, object> parameter = new Dictionary<string, object>()
            //        {
            //                { "tenantID", _parameterStatic.CollectionItemsParameter.ProductionLineNo },//租户ID,//产线编号
            //                { "equipCode", _parameterStatic.CollectionItemsParameter.EquipNum },//设备编号
            //                { "operateId", _temporaryStatic.Mes_Account},//操作者ID
            //                { "manualStatus", device_status == 4 ? 0 :1 },//手自动状态（0：手动；1：自动）
            //                { "runStatus",  device_status == 1 ? 1 :0  },//运行状态（0：非运行；1：运行）
            //                { "waitStatus",  device_status == 2 ? 1 :0 },//待机状态（0：非待机；1：待机）
            //                { "faultStatus",  device_status == 5 ? 1 :0 },//故障状态（0：非故障；1：故障）
            //                { "repairStatus",  device_status == 6 ? 1 :0 },//维修状态（0：非维修；1：维修）
            //                { "stopStatus",  device_status == 7 ? 1 :0  },//急停状态（0：非急停；1：急停）
            //                { "mesConnectStatus", 1 },//与MES通讯状态（0：状态异常；1：状态正常）
            //                { "warnSign",  device_status == 3 ? 1 :0  },//报警指示灯状态（0：无报警指示；1：报警指示）
            //                { "equipSign", equipSign },//设备状态指示牌（带反馈）（0：停机；1：运行；2：待机；3：故障；4：维修；5：急停；6：其它）
            //                { "equipMesStatus", _parameterStatic.DecideParameter.EnableMES?0:1 },//设备MES状态（0：未屏蔽MES上位机或者扫码枪；1：屏蔽）
            //                { "warningStatus", device_status == 3 ? 1 :0},//报警喇叭状态（0：喇叭停止；1：喇叭报警）
            //        };

            //            param.Add("parameter", parameter);
            //            try
            //            {
            //                interaction.Interaction(_parameterStatic.MESParameter.BaseUrl + _parameterStatic.MESParameter.OeeStatusRouter,
            //                    _parameterStatic.MESParameter.OeeStatusTime,
            //                    _parameterStatic.MESParameter.OeeStatusNumber,
            //                    DateTime.Now, null, param);
            //            }
            //            catch (Exception)
            //            {
            //            }
            //            param.Remove("parameter");
            //            Thread.Sleep(_parameterStatic.RunParameter.DeviceStatusTime * 1000);
            //        }
            //    }), service_name);
            //}
        }


     
    }
}
